package com.tang.client;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.socket.SocketChannel;
import lombok.extern.slf4j.Slf4j;

import java.time.LocalDateTime;
import java.util.Random;

@Slf4j
public class MyInMsgHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        SocketChannel channel = (SocketChannel) ctx.channel();
        log.info("连接报告开始");
        log.info("连接报告信息：本地客户端连接到服务器，channelId: {}", channel.id());
        log.info("连接报告IP: {}", channel.remoteAddress().getHostString());
        log.info("连接报告Port: {}", channel.remoteAddress().getPort());
        log.info("连接报告完毕");
        // 通知客户端连接建立成功
        String str = "通知服务端连接建立成功 " + LocalDateTime.now() + " " + channel.localAddress().getHostString() + "\r\n";
        ctx.writeAndFlush(str);
    }

    /**
     * 当客户端主动断开服务器连接后
     *
     * @param ctx 连接对象
     * @throws Exception 异常
     */
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        log.info("断开连接： {}", ctx.channel().localAddress());
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        log.info("{} 客户端收到消息：{}", LocalDateTime.now(), msg);
        // 通知客户端消息发送成功
        Random random = new Random(10);
        String str = "随机数：" + random.nextInt() + "\r\n";
        ctx.writeAndFlush(str);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
        log.error("异常信息:\r\n{}", cause.getMessage());
    }
    
}
